package com.aqie.seller.service;

import com.aqie.api.ProductRpc;
import com.aqie.api.domain.ProductRpcReq;
import com.aqie.entity.Product;
import com.aqie.entity.enums.ProductStatus;
import com.hazelcast.core.HazelcastInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 产品缓存 相关功能
 *  当前类中调用 Cacheable，CachePut这些方法没有作用
 *  so 初始化缓存方法放入到service中
 */
@Component      // 添加spring注解
public class ProductCache {
    static final String CACHE_NAME = "aqie_product";
    private static Logger LOG = LoggerFactory.getLogger(ProductCache.class);

    @Autowired
    private ProductRpc productRpc;

    @Autowired
    private HazelcastInstance hazelcastInstance;

    /**
     *  读取缓存
     * @param id 产品id
     * @return 缓存对象
     */
    @Cacheable(cacheNames = CACHE_NAME)
    public Product readCache(String id){
        LOG.info("rpc查询单个产品,请求:{}", id);
        Product result = productRpc.findOne(id);
        LOG.info("rpc查询单个产品,结果:{}", result);
        return result;
    }

    // 更新缓存
    @CachePut(cacheNames = CACHE_NAME,key = "#product.id")
    public Product putCache(Product product){
        return product;
    }

    // 移除缓存
    @CacheEvict(cacheNames = CACHE_NAME)
    public void removeCache(String id){}

    public List<Product> readAllCache(){
        // map名称就是缓存名称 ， map里面所有value就是全部产品
        Map map = hazelcastInstance.getMap(CACHE_NAME);
        List<Product> products = null;
        // 有缓存数据时
        if(map.size() >0 ){
            products = new ArrayList<>();
            products.addAll(map.values());  // 将所有产品加入缓存
        }else {     // 缓存没数据，直接查询
            products = findAll();
        }
        return products;
    }

    /**
     * 查询全部产品
     * @return
     */
    public List<Product> findAll(){
        ProductRpcReq req = new ProductRpcReq();
        List<String> status = new ArrayList<>();
        status.add(ProductStatus.IN_SELL.name());
        req.setStatusList(status);

        LOG.info("rpc查询全部产品,请求:{}", req);
        List<Product> result = productRpc.query(req);
        LOG.info("rpc查询全部产品,结果:{}", result);
        return result;
    }
}
